﻿using System;
using System.ServiceModel.Dispatcher;
using System.ServiceModel;
using System.ServiceModel.Channels;
using GianosNET.Common.CommonUtils;

namespace GianosNET.Common.ClientUtils
{
    /// <summary>
    /// This is the client inspector class that is used to intercept the message on the
    /// client side, before/after any request is made to the server.
    /// </summary>
    public class ClientMessageInspector : IClientMessageInspector
    {
        /// <summary>
        /// This method will be called from the client side just before any method is called.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="channel"></param>
        /// <returns></returns>
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            // Prepare the request message copy to be modified
            MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
            request = buffer.CreateMessage();
            
            CustomHeaderData customData = new CustomHeaderData();

            customData.AuthenticationToken = ClientContext.Token;

            CustomHeader header = new CustomHeader(customData);

            // Add the custom header to the request.
            request.Headers.Add(header);

            return null;
        }

        /// <summary>
        /// This method will be called after completion of a request to the server.
        /// </summary>
        /// <param name="reply"></param>
        /// <param name="correlationState"></param>
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            // Read the header to find if server has returned any 
            // custom data to the client.
            CustomHeaderData customData = CustomHeader.ReadHeader(reply);

            if (customData != null)
            {
                // Read custom data
                object o = customData.AnyCustomData;

                // This is just to demonstrate returning headers from
                // server to client. 
            }
        }
    }
}